#pragma once
#include "Protocol.hpp"

class Calculator
{
public:
    Calculator()
    {
    }
    ~Calculator()
    {
    }

    Response Execute(const Request req)
    {
        Response res;
        switch (req.GetOp())
        {
        case '+':
            res.SetResult(req.GetX() + req.GetY());
            break;
        case '-':
            res.SetResult(req.GetX() - req.GetY());
            break;
        case '*':
            res.SetResult(req.GetX() * req.GetY());
            break;
        case '/':
            {
                if(req.GetY() == 0)
                    res.SetCode(1);     //除0错误
                else
                    res.SetResult(req.GetX() / req.GetY());
            }
            break;
        case '%':
            {
                if(req.GetY() == 0)
                    res.SetCode(2);     //模0错误
                else
                    res.SetResult(req.GetX() % req.GetY());
            }
            break;
        default:
            res.SetCode(3);     //运算符无法识别
            break;
        }
        return res;
    }
};


Calculator _cal;

string Entry(string &package)
{
    string message;
    string respstr;
    // 1.判断报文的完整性
    while (Decode(package, &message))
    {
        LOG(LogGrade::NORMAL) << "Content:\n"
                              << message;
        if (message.empty())
            break;
        // 2. 反序列化  message 曾经被序列化过了
        Request req;
        if (!req.DeSerialize(message))
        {
            LOG(LogGrade::ERROR) << "反序列化失败";
            break;
        }

        cout << "===============" << endl;
        req.Print();
        cout << "===============" << endl;

        // 3. 计算结果
        Response res = _cal.Execute(req);
        // 4 .序列化
        string tmp;
        res.Serialize(tmp);
        LOG(LogGrade::NORMAL) << tmp;

        // 5. 添加长度报头
        Encode(tmp);
        LOG(LogGrade::NORMAL) << tmp;
        // 6. 拼接应答（一条报文中有多条计算）
        respstr += tmp;
    }
    return respstr; // 报文不完整，直接返回空串
}